<?php
namespace App\Http\Controllers;

use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use Validator;
use App\Tools\Excel;

abstract class Controller extends BaseController
{
	/**
	 * 获取分页信息
	 *
	 * @param  $total 总数
	 * @param  $cur   当前页
	 * @param  $size  每页显示数量
	 */
	public function page($total,$cur=1,$size=15)
	{
		if($cur<1)
			$cur=1;
		$pages=ceil($total/$size);
		if($cur>$pages)
			$cur=$pages;
		return [
			'CurPage'=>$cur,
			'PageSize'=>$size,
			'PageNum'=>$pages,
			'Total'=>$total,
		];
	}
	/**
	 * 从客户端请求获取页码和每页显示数量
	 */
	public function getPage($data)
	{
		$size=!empty($data['PageSize']) && +$data['PageSize'] ? +$data['PageSize'] : 10;
		$page=!empty($data['Page']) && +$data['Page']>1 ? +$data['Page'] : 1;
		$export=!empty($data['Export']) && ($data['Export']=='true' || $data['Export']=='detailTrue');
		return [$page,$size,$export];
	}
	/**
	 * 校验参数
	 *
	 * @param  $req   Request
	 * @param  $rules 校验规则
	 * @param  $msg   错误消息
	 * @param  $attr  指定属性
	 */
	public function check(Request $req,array $rules,array $msg,array $attr=[])
	{
		$validator= Validator::make($req->input(),$rules,$msg);
		if($validator->fails())
			$this->throwValidationException($req,$validator);
	}
	/**
	 * 导出数据
	 *
	 * @param $data 数据
	 * @param $filename 文件名
	 */
	public function export($data,$filename='data')
	{
		Excel::export($data,$filename);
		exit;
	}
}
